#include "LoginDialog.h"

LoginDialog::LoginDialog(QDialog *parent)
    : QDialog(parent)
{
	ui.setupUi(this);

	setWindowFlags(Qt::WindowStaysOnTopHint);
	QObject::connect(ui.closeButton, SIGNAL(clicked()), this, SLOT(accept()));
	QObject::connect(ui.newAccountButton, SIGNAL(clicked()), this, SLOT(newUser()));
	QObject::connect(ui.deleteAccountButton, SIGNAL(clicked()), this, SLOT(deleteUser()));
	QObject::connect(ui.usrList, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(accountSelected(QListWidgetItem*)));
	QObject::connect(ui.loginButton, SIGNAL(clicked()), this, SLOT(login()));
	QObject::connect(this, SIGNAL(itemActivated(QListWidgetItem*)), ui.usrList, SIGNAL(itemActivated(QListWidgetItem*)));

	QShortcut* closeShortcut = new QShortcut(QKeySequence(Qt::Key_Escape),  this);
	QObject::connect(closeShortcut,SIGNAL(activated()),this,SLOT(accept()));

	setAccountTable();
}

LoginDialog::~LoginDialog()
{

}

void LoginDialog::setAccountTable()
{
	ui.usrList->clear();
	mUsers.clear();
	QDir dir = QDir::current();
	dir.cd("data");
	dir.cd("users");
	//QStringList filters;
	//filters << "*.db";
	//dir.setNameFilters(filters);
	QStringList files = dir.entryList(QStringList() ,QDir::Dirs);
	for (int i=0; i<files.size(); i++)
	{
		if (files[i]!=QString("..") && files[i]!=QString("."))
		{
			cout<<"LoginDialog::setAccountTable->file["<<i<<"]="<<files[i].toUtf8().data()<<endl;
			QString usr = files[i];
			//usr.remove(".db");
			mUsers<<usr;
			//mUsers.push_back(usr);
			ui.usrList->addItem(usr);
		}
	}

	if (!OPT.lastAccount.isEmpty())
	{
		QList<QListWidgetItem*> usrs = ui.usrList->findItems(OPT.lastAccount, Qt::MatchExactly);
		if (usrs.isEmpty())
		{
			cout<<"LoginDialog::setAccountTable-->Invalid OPT.lastAccount: "<<OPT.lastAccount.toUtf8().data()<<endl;
			OPT.lastAccount.clear();
		}
		else
		{
			ui.usrNameEdit->setText(OPT.lastAccount);
			usrs[0]->setSelected(true);
			emit itemActivated(usrs[0]);
		}
	}
}

void LoginDialog::login()
{
	QString usrPath = "./data/users/";
	QString comFilePath = "./data/common/";
	mCurUser = ui.usrNameEdit->text();
	bool findUsr = false;
	for (int i=0; i<mUsers.size(); i++)
		if (mUsers[i] == mCurUser)
			findUsr = true;

	if (!findUsr)
	{
		QString message="Please select a VALID account and login.";
		MessageBox::showWarning(QMessageBox::Warning,QString("Warning!"),message,12,this);
		return;
	}

	if (!DB.mUsrMain.isEmpty())
		DB.closeDB(DB.mUsrMain);

	OPT.lastAccount = mCurUser;
	DB.mUsrMain = mCurUser;
	usrPath = usrPath + mCurUser + "/";
	if (!DB.openDB(usrPath, mCurUser))
		assert(0);

	OPT.hasLogined=true;
	//emit loginSig();
	this->accept();
}

void LoginDialog::accountSelected(QListWidgetItem* item)
{
	QString selectedUsr = item->text();
	//mCurUser = selectedUsr;
	OPT.lastAccount = selectedUsr;
	ui.usrNameEdit->setText(selectedUsr);
}

void LoginDialog::newUser()
{
	cout<<"LoginDialog::newUser"<<endl;
	QString newUsrName = ui.usrNameEdit->text();
	if (mUsers.contains(newUsrName))
	{
		QString message="This user already exists.";
		MessageBox::showWarning(QMessageBox::Warning,QString("Warning!"),message,12,this);
		return;
	}

	QDir curDir = QDir::current();
	curDir.mkdir(QString("./data/users/")+newUsrName);
	QString oldFile = QString("./data/users/new.db");
	QString newFile = QString("./data/users/")+newUsrName+"/"+newUsrName+".db";
	cout<<"LoginDialog::oldFile-->oldFile="<<oldFile.toUtf8().data()<<endl;
	cout<<"LoginDialog::newFile-->newFile="<<newFile.toUtf8().data()<<endl;
	if (!QFile::copy(oldFile, newFile))
	{
		cout<<"LoginDialog::newUser-->Fail to copy file."<<endl;
		assert(0);
	}

	OPT.lastAccount = newUsrName;
	setAccountTable();
}

void LoginDialog::deleteUser()
{
	cout<<"LoginDialog::deleteUser"<<endl;
	QString usrToDelete = ui.usrNameEdit->text();
	QString message=QString("Are you sure to delete user '%1'?").arg(usrToDelete);
	if (MessageBox::showConfirm(QMessageBox::Warning,QString("Warning!"),message,12,this) == 0x00004000) //QMessageBox::Yes
	{
		if (usrToDelete == OPT.lastAccount)
		{
			//WM.finishLastTask();
			OPT.lastAccount.clear();
		}

		QDir curDir = QDir::current();
		//delete user
		QDir dir = QDir::current();
		dir.cd("data");
		dir.cd("users");
		dir.cd(usrToDelete);
		QStringList files = dir.entryList(QStringList());
		for (int i=0; i<files.size(); i++)
			dir.remove(files[i]);

		QString rmDir = QString("./data/users/")+usrToDelete;
		if(!curDir.rmdir(rmDir))
		{
			cout<<"LoginDialog::deleteUser-->Error! Cannot remove directory."<<endl;
			assert(0);
		}

		ui.usrNameEdit->clear();
		setAccountTable();
	}
}
